package gate.handler;

import com.google.protobuf.Message;
import gate.ClientMessager;
import gate.client.ClientConnection;
import gate.client.ClientConnectionMap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by tianfei on 2017/4/17.
 */
public class GateServerHandler extends SimpleChannelInboundHandler<Message> {
    private static final Logger logger = LoggerFactory.getLogger(GateServerHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //在客户端完成鉴权之后再保存客户端连接

        ClientConnectionMap.addClientConnection(ctx);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Message message) throws Exception {
        ClientConnection conn = ClientConnectionMap.getClientConnection(channelHandlerContext);
        ClientMessager.processTransferHandler(message, conn);

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {

        //fixme 实现心跳机制

        ClientConnectionMap.removeClientConnection(ctx);
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("exceptionCaught in "+ctx+" : "+cause);

        ClientConnectionMap.removeClientConnection(ctx);
        ctx.close();

    }
}
